# Flask框架导入
from flask import render_template, redirect, url_for, flash, request, session

# WTForms表单相关导入
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField
from wtforms.validators import DataRequired, Length

# 本地模块导入
from . import auth_bp
from .services import login_user, logout_user, wechat_login
from ..utils import member_login_required
from .wechat import WechatAuth

# 数据库模型导入
from inc.models import AdminMember, WechatConfig, OperationLog

# 工具函数导入
from ..utils.helpers import get_current_member, get_accessible_menus

class MemberLoginForm(FlaskForm):
    """会员登录表单"""
    username = StringField('用户名/手机号/邮箱', validators=[DataRequired(), Length(max=50)])
    password = PasswordField('密码', validators=[DataRequired(), Length(min=6, max=20)])
    remember_me = BooleanField('记住我')

@auth_bp.context_processor
def inject_menus():
    """注入可访问菜单到模板上下文"""
    member = get_current_member()
    if member:
        return dict(accessible_menus=get_accessible_menus(member.id))
    return dict(accessible_menus=[])


@auth_bp.route('/login', methods=['GET', 'POST'])
def login():
    """会员登录"""
    # 如果会员已登录，直接重定向到首页
    if 'member_id' in session:
        return redirect(url_for('member.index'))

    form = MemberLoginForm()
    config = WechatConfig.query.first()

    # 处理扫码登录请求
    if request.args.get('action') == 'wechat_login':
        if not config or not config.login_enabled:
            flash('扫码登录未启用', 'danger')
            return redirect(url_for('member.login'))

        # 生成随机state参数
        from secrets import token_urlsafe
        state = token_urlsafe(16)
        session['wechat_login_state'] = state

        # 构建扫码登录URL
        redirect_uri = url_for('member.auth.wechat_login_callback', _external=True)
        if config.login_redirect_uri:
            redirect_uri = config.login_redirect_uri

        auth_url = f"https://open.work.weixin.qq.com/wwopen/sso/qrConnect?appid={config.corp_id}&agentid={config.agent_id}&redirect_uri={redirect_uri}&state={state}"
        return render_template('member/auth/login.html',
                               form=form,
                               WechatConfig=config,
                               show_qrcode=True,
                               auth_url=auth_url)

    # 处理表单提交
    if form.validate_on_submit():
        member = login_user(
            username=form.username.data,
            password=form.password.data,
            ip_address=request.remote_addr
        )

        if member:
            session['member_id'] = member.id
            session['member_name'] = member.name
            flash('登录成功！', 'success')
            next_page = request.args.get('next') or url_for('member.index')
            return redirect(next_page)
        else:
            flash('用户名或密码错误或账号已被禁用！', 'danger')

    return render_template('member/auth/login.html',
                           form=form,
                           WechatConfig=config,
                           show_qrcode=False)

@auth_bp.route('/wechat_login/callback')
def wechat_login_callback():
    """前台扫码登录回调"""
    state = request.args.get('state')
    code = request.args.get('code')
    config = WechatConfig.query.first()

    if not config:
        flash('企业微信配置未找到', 'danger')
        return redirect(url_for('member.auth.login'))

    member = wechat_login(
        state=state,
        code=code,
        config=config,
        ip_address=request.remote_addr
    )

    if not member:
        return redirect(url_for('member.auth.login'))

    # 登录用户
    session['member_id'] = member.id
    session['member_name'] = member.name
    flash('扫码登录成功', 'success')
    return redirect(url_for('member.index'))

@auth_bp.route('/logout')
@member_login_required
def logout():
    """退出登录"""
    if 'member_id' in session:
        member_name = session.get('member_name', '未知会员')
        logout_user(member_name, ip_address=request.remote_addr)
        session.pop('member_id', None)
        session.pop('member_name', None)
        flash('您已成功退出登录。', 'info')
    return redirect(url_for('member.auth.login'))
